/*
 * SessionReenviosInconsistenciaBean.java
 *
 * Created on June 21, 2007, 3:12 PM
 * Copyright fsanchez
 */
package gestionportletreenviosinconsistencia;

import com.src.computec.inconsistencias.constantes.ConstantesGenerales;
import com.src.computec.inconsistencias.delegate.InconsistenciasDelegate;
import com.src.computec.inconsistencias.exception.InconsistenciasException;
import com.src.computec.inconsistencias.source.InconsistenciasSource;
import com.src.computec.radar.base.ldap.dto.LdapUserDto;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.services.utilities.consultas.delegate.ConsultasDelegate;
import com.src.computec.radar.services.utilities.consultas.exception.ConsultasException;
import com.src.computec.radar.services.utilities.dto.ClienteDto;
import com.src.computec.radar.services.utilities.dto.NodoDto;
import com.src.computec.radar.services.utilities.dto.ProductoDto;
import com.src.computec.radar.services.utilities.dto.ProveedorDto;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import com.sun.rave.web.ui.model.MultipleSelectOptionsList;
import com.sun.rave.web.ui.model.Option;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;


/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 */
public class SessionReenviosInconsistenciaBean extends AbstractSessionBean {
    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
    private int __placeholder;
    private String ldapUser;
    private Option[] clienteOptions=null;
    private Option[] productoOptions;
    private Option[] cicloOptions;
    private Option[] nodoOptions;
    private Option[] empresaMensOptions;
    private boolean empresaMensajeria;
    private boolean noEmpresaMensajeria;
    
    private List paramSearch;
    private List searchResult;
    private String proveedorEM;
    private Calendar minDate;
    private Calendar maxDate;
    private String codigoProveedor;
    private boolean renderedTablaReenvios=false;
    private boolean renderedOrdenesProceso=false;
    private boolean renderedAlert=false;
    private boolean renderedSpacerOrdenesProceso=true;
    private boolean renderedButtonGenerarArchivo=true;
    private Date actualDate=null;
    
    private MultipleSelectOptionsList mSelectOpListNumOrdenes = new MultipleSelectOptionsList();
    private String[] select;
    
    
    private String reenviosTotal="0";
    private String reenviosTotPend="0";
    private String porcentajePend="0 %";
    private String reenviosTotEfectivos="0";
    private String porcentajeEfectivos="0 %";
    private String reenviosTotNoEfectivos="0";
    private String porcentajeNoEfectivos="0 %";
    
    
    //PAGINACION
    private boolean paginacion = false;
    private int incrementoIntervalosPaginacion = 0;
    private String numeroRegistrosPaginados = new String();
    private String pagina = new String();
    private int sizeDataTable = 0;
    private int rowsDataTable = 0;
    private int first = 0;
    //FIN PAGINACION
    
    
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>


    /** 
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionReenviosInconsistenciaBean() {
      //  this.setLdapUser("fsanchez.computec");            
	this.ldapUser = this.getUIdByDomainName(FacesPortletUtil.getPortletRequest(FacesContext.getCurrentInstance()).getRemoteUser());
	this.setLdapUser(ldapUser);            
	
	
	setActualDate(new Date(System.currentTimeMillis()));
	
	this.setClienteOptions(this.getClientesOptions());
	this.setProductoOptions(this.getProductosOptions(""));
	this.setCicloOptions(this.getCiclosOptions());
	
	this.empresaMensajeria=false;
	this.setNoEmpresaMensajeria(true);
	try{
	    setCodigoProveedor(this.findRolesUser());
	    if(empresaMensajeria){
		ProveedorDto provDto_=new ProveedorDto();
		provDto_.setCodigoProveedor(getCodigoProveedor());
		InconsistenciasDelegate delegate_=new InconsistenciasDelegate();
		this.setProveedorEM(delegate_.getRazonSocialProveedor(provDto_).getRazonSocial());
		this.setAllNodosEmpresaMensajeriaOptions(provDto_);
		this.setNoEmpresaMensajeria(!this.empresaMensajeria);
	    }
	}catch(ConsultasException e){
	    e.printStackTrace();
	}catch(InconsistenciasException e){
	    e.printStackTrace();
	}
	
	if(isNoEmpresaMensajeria()){
	    this.empresaMensOptions=this.getAllEmpresaMensajeriaOptions();
	    this.setAllNodosEmpresaMensajeriaOptions(null);
	}
	
	
	setMinDate(Calendar.getInstance());
	getMinDate().setTimeInMillis(System.currentTimeMillis());
	getMinDate().add(Calendar.MONTH, -6);
	
	setMaxDate(Calendar.getInstance());
	getMaxDate().setTimeInMillis(System.currentTimeMillis());
	
	//PAGINACION 
	this.incrementoIntervalosPaginacion = Integer.valueOf(InconsistenciasSource.getInstance().getInconsistenciasSetupKey("incrementoIntervalosPaginacion")).intValue();
        this.numeroRegistrosPaginados = InconsistenciasSource.getInstance().getInconsistenciasSetupKey("incrementoIntervalosPaginacion");
        this.pagina = "1";
        this.rowsDataTable = this.getIncrementoIntervalosPaginacion();
	//FIN PAGINACION
    }

    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationReenviosInconsistenciaBean getApplicationReenviosInconsistenciaBean() {
        return (ApplicationReenviosInconsistenciaBean)getBean("ApplicationReenviosInconsistenciaBean");
    }


    /** 
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here

    }

    /** 
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    public void passivate() {
    }

    /** 
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    public void activate() {
    }

    /** 
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    public void destroy() {
    }
    
    public Option[] getClientesOptions() 
    {
        try
        {
            ConsultasDelegate delegate = new ConsultasDelegate();
            
            List lstClientes = delegate.getClientes();
            
            Option[] optionsAux = new Option[ lstClientes.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = lstClientes.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
                ClienteDto dto = (ClienteDto)iter.next();
                optionsAux[i] = new Option(dto.getCodigoCliente(),dto.getRazonSocial());
            }   
            
            return optionsAux;            
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }

    
    public Option[] getProductosOptions(String pCodigoCliente) 
    {
	Option[] optionsAux =null;
        try
        {
	    if(pCodigoCliente != null && !pCodigoCliente.equals(""))
            {            
		ConsultasDelegate delegate = new ConsultasDelegate();
		ClienteDto clienteDto_=new ClienteDto();
		clienteDto_.setCodigoCliente(pCodigoCliente);
		List lstProductos = delegate.getProductosByCliente(clienteDto_);

		optionsAux = new Option[ lstProductos.size() + 1 ];            
		optionsAux[0] = new Option("","Seleccione...");     

		Iterator iter = lstProductos.iterator();

		for(int i = 1; iter.hasNext(); i++)
		{
		    ProductoDto dto = (ProductoDto)iter.next();
		    optionsAux[i] = new Option(dto.getCodigoProducto(),dto.getDescripcionProducto());
		}   
	    }else{
		optionsAux = new Option[1];            
                optionsAux[0] = new Option("","Seleccione..."); 
	    }
            
            return optionsAux;            
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    public Option[] getCiclosOptions() 
    {
	Option[] optionsAux =null;
        try
        {
	    
	
	optionsAux = new Option[ 101 ];            
	optionsAux[0] = new Option("","Seleccione...");     

	

	for(int i = 1; i<=100; i++)
	{
	    optionsAux[i] = new Option(""+i,""+i);
	}   
	  
            
            return optionsAux;            
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    
    public void setAllNodosEmpresaMensajeriaOptions(ProveedorDto proveedorDto) 
    {
        Option[] optionsAux = null;
        
        try
        {     
            if(proveedorDto != null)
            {            
                ConsultasDelegate delegate = new ConsultasDelegate();

                List lstNodos = delegate.getNodosByProveedor(proveedorDto);

                optionsAux = new Option[ lstNodos.size() + 1 ];            
                optionsAux[0] = new Option("","Seleccione...");     

                Iterator iter = lstNodos.iterator();

                for(int i = 1; iter.hasNext(); i++)
                {
                    NodoDto dto = (NodoDto)iter.next();
                    optionsAux[i] = new Option( dto.getCodigoNodo(),
                                                dto.getNombreNodo());
                }           
            }
            else
            {
                optionsAux = new Option[1];            
                optionsAux[0] = new Option("","Seleccione..."); 
            }
            this.nodoOptions = optionsAux;            
        }
        catch(Exception e)
        {
            this.nodoOptions = null;                    
            e.printStackTrace();           
        }        
    }
     
    private String getUIdByDomainName(String domainName) {
        String[] tokens =  domainName.split(",");
        if (tokens.length > 0) {
            String[] uIdTokens = (tokens[0]).split("=");
            if (uIdTokens.length == 2) {
                return uIdTokens[1];
            }
        }
        return "";
    }
    
    public Option[] getAllEmpresaMensajeriaOptions() 
    {
        try
        {
            ConsultasDelegate delegate = new ConsultasDelegate();
            
            List lstProveedores = delegate.getProveedoresEmpresaMensajeria();
            
            Option[] optionsAux = new Option[ lstProveedores.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = lstProveedores.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
                ProveedorDto dto = (ProveedorDto)iter.next();
                optionsAux[i] = new Option(dto.getCodigoProveedor(),dto.getRazonSocial());
            }   
            
            return optionsAux;            
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    
   public String findRolesUser() throws ConsultasException {
        ConsultasDelegate consultasDelegate = new ConsultasDelegate();
	String codigoEM=ConstantesGenerales.CODIGO_PROVEEDOR_COMPUTEC;
        LdapUserDto ldapUserDtoAux = new LdapUserDto();
        ldapUserDtoAux.setIdLdap(this.getLdapUser());
        ldapUserDtoAux = consultasDelegate.getLdapUserByPrimaryKey(ldapUserDtoAux);
        //this.ldapUserDto = ldapUserDtoAux;
        Iterator iterRoles = ldapUserDtoAux.getRoles().iterator();	
        while(iterRoles.hasNext()) {
            String nombreRole = (String) iterRoles.next();
            if (nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_empresa_mensajeria_cn")) == 0) {
               this.empresaMensajeria = true;
		codigoEM=ldapUserDtoAux.getCodigoEmpresaMensajeria();		
            }
        }
	return codigoEM;
    }
    
    public Option[] getClienteOptions() {
        return clienteOptions;
    }

    public void setClienteOptions(Option[] clienteOptions) {
        this.clienteOptions = clienteOptions;
    }

    public Option[] getProductoOptions() {
        return productoOptions;
    }

    public void setProductoOptions(Option[] productoOptions) {
        this.productoOptions = productoOptions;
    }

    public Option[] getCicloOptions() {
        return cicloOptions;
    }

    public void setCicloOptions(Option[] cicloOptions) {
        this.cicloOptions = cicloOptions;
    }

    public Option[] getNodoOptions() {
        return nodoOptions;
    }

    public void setNodoOptions(Option[] nodoOptions) {
        this.nodoOptions = nodoOptions;
    }

    public boolean isEmpresaMensajeria() {
        return empresaMensajeria;
    }

    public void setEmpresaMensajeria(boolean empresaMensajeria) {
        this.empresaMensajeria = empresaMensajeria;
    }

    public String getProveedorEM() {
        return proveedorEM;
    }

    public void setProveedorEM(String proveedorEM) {
        this.proveedorEM = proveedorEM;
    }

    public Option[] getEmpresaMensOptions() {
        return empresaMensOptions;
    }

    public void setEmpresaMensOptions(Option[] empresaMensOptions) {
        this.empresaMensOptions = empresaMensOptions;
    }

    public boolean isNoEmpresaMensajeria() {
        return noEmpresaMensajeria;
    }

    public void setNoEmpresaMensajeria(boolean noEmpresaMensajeria) {
        this.noEmpresaMensajeria = noEmpresaMensajeria;
    }

    public Calendar getMinDate() {
        return minDate;
    }
    
    public Date getMinimoDate() {
        return minDate.getTime();
    }

    public void setMinDate(Calendar minDate) {
        this.minDate = minDate;
    }

    
    public Calendar getMaxDate() {
        return maxDate;
    }
    
    public Date getMaximoDate() {
        return maxDate.getTime();
    }

    public void setMaxDate(Calendar maxDate) {
        this.maxDate = maxDate;
    }


    public MultipleSelectOptionsList getMSelectOpListNumOrdenes() {
        return mSelectOpListNumOrdenes;
    }

    public void setMSelectOpListNumOrdenes(MultipleSelectOptionsList mSelectOpListNumOrdenes) {
        this.mSelectOpListNumOrdenes = mSelectOpListNumOrdenes;
    }

    public List getSearchResult() {
        return searchResult;
    }

    public void setSearchResult(List searchResult) {
        this.searchResult = searchResult;
    }

    public boolean isRenderedTablaReenvios() {
        return renderedTablaReenvios;
    }

    public void setRenderedTablaReenvios(boolean renderedTablaReenvios) {
        this.renderedTablaReenvios = renderedTablaReenvios;
    }

    public boolean isRenderedOrdenesProceso() {
        return renderedOrdenesProceso;
    }

    public void setRenderedOrdenesProceso(boolean renderedOrdenesProceso) {
        this.renderedOrdenesProceso = renderedOrdenesProceso;
    }

    public boolean isRenderedAlert() {
        return renderedAlert;
    }

    public void setRenderedAlert(boolean renderedAlert) {
        this.renderedAlert = renderedAlert;
    }

    public boolean isRenderedSpacerOrdenesProceso() {
        return renderedSpacerOrdenesProceso;
    }

    public void setRenderedSpacerOrdenesProceso(boolean renderedSpacerOrdenesProceso) {
        this.renderedSpacerOrdenesProceso = renderedSpacerOrdenesProceso;
    }

    public String getCodigoProveedor() {
        return codigoProveedor;
    }

    public void setCodigoProveedor(String codigoProveedor) {
        this.codigoProveedor = codigoProveedor;
    }

    public List getParamSearch() {
        return paramSearch;
    }

    public void setParamSearch(List paramSearch) {
        this.paramSearch = paramSearch;
    }

    public String getLdapUser() {
        return ldapUser;
    }

    public void setLdapUser(String ldapUser) {
        this.ldapUser = ldapUser;
    }

    public Date getActualDate() {
        return actualDate;
    }

    public void setActualDate(Date actualDate) {
        this.actualDate = actualDate;
    }

    public String[] getSelect() {
        return select;
    }

    public void setSelect(String[] select) {
        this.select = select;
    }

    public boolean isRenderedButtonGenerarArchivo() {
        return renderedButtonGenerarArchivo;
    }

    public void setRenderedButtonGenerarArchivo(boolean renderedButtonGenerarArchivo) {
        this.renderedButtonGenerarArchivo = renderedButtonGenerarArchivo;
    }

    public String getReenviosTotal() {
        return reenviosTotal;
    }

    public void setReenviosTotal(String reenviosTotal) {
        this.reenviosTotal = reenviosTotal;
    }

    public String getReenviosTotPend() {
        return reenviosTotPend;
    }

    public void setReenviosTotPend(String reenviosTotPend) {
        this.reenviosTotPend = reenviosTotPend;
    }

    public String getPorcentajePend() {
        return porcentajePend;
    }

    public void setPorcentajePend(String porcentajePend) {
        this.porcentajePend = porcentajePend;
    }

    public String getReenviosTotEfectivos() {
        return reenviosTotEfectivos;
    }

    public void setReenviosTotEfectivos(String reenviosTotEfectivos) {
        this.reenviosTotEfectivos = reenviosTotEfectivos;
    }

    public String getPorcentajeEfectivos() {
        return porcentajeEfectivos;
    }

    public void setPorcentajeEfectivos(String porcentajeEfectivos) {
        this.porcentajeEfectivos = porcentajeEfectivos;
    }

    public String getReenviosTotNoEfectivos() {
        return reenviosTotNoEfectivos;
    }

    public void setReenviosTotNoEfectivos(String reenviosTotNoEfectivos) {
        this.reenviosTotNoEfectivos = reenviosTotNoEfectivos;
    }

    public String getPorcentajeNoEfectivos() {
        return porcentajeNoEfectivos;
    }

    public void setPorcentajeNoEfectivos(String porcentajeNoEfectivos) {
        this.porcentajeNoEfectivos = porcentajeNoEfectivos;
    }

    public boolean isPaginacion() {
        return paginacion;
    }

    public void setPaginacion(boolean paginacion) {
        this.paginacion = paginacion;
    }

    public int getIncrementoIntervalosPaginacion() {
        return incrementoIntervalosPaginacion;
    }

    public void setIncrementoIntervalosPaginacion(int incrementoIntervalosPaginacion) {
        this.incrementoIntervalosPaginacion = incrementoIntervalosPaginacion;
    }

    public String getNumeroRegistrosPaginados() {
        return numeroRegistrosPaginados;
    }

    public void setNumeroRegistrosPaginados(String numeroRegistrosPaginados) {
        this.numeroRegistrosPaginados = numeroRegistrosPaginados;
    }

    public String getPagina() {
        return pagina;
    }

    public void setPagina(String pagina) {
        this.pagina = pagina;
    }

    public int getSizeDataTable() {
        return sizeDataTable;
    }

    public void setSizeDataTable(int sizeDataTable) {
        this.sizeDataTable = sizeDataTable;
    }

    public int getRowsDataTable() {
        return rowsDataTable;
    }

    public void setRowsDataTable(int rowsDataTable) {
        this.rowsDataTable = rowsDataTable;
    }

    public int getFirst() {
        return first;
    }

    public void setFirst(int first) {
        this.first = first;
    }
}
